<script>
    var jqgridAllColsArr = ['goodsName', 'goodsSn', 'barCode', 'colorName', 'sizeName', 'categoryId', 'quantity', 'price', 'discount', 'truePrice', 'amount', 'trueAmount', 'purchasePrice', 'costTotal', 'businessTime', 'ordersSn', 'salerName', 'clientName', 'trueTotalAmount', 'adjustmentsTotal', 'grossProfit', 'grossProfitRate', 'alreadyPaid', 'blandName', 'wipeZero', 'styleName', 'seasonName', 'year', 'storeName'];
    var detailListShowColsArr = ['goodsName', 'goodsSn', 'barCode', 'colorName', 'sizeName', 'categoryId', 'quantity', 'price', 'discount', 'truePrice', 'amount', 'trueAmount', 'purchasePrice', 'costTotal', 'businessTime', 'ordersSn', 'salerName', 'clientName', 'trueTotalAmount', 'grossProfit', 'grossProfitRate', 'alreadyPaid', 'blandName', 'styleName', 'seasonName', 'year', 'storeName'];
    var groupBySkuListShowColsArr = ['goodsName', 'goodsSn', 'barCode', 'colorName', 'sizeName', 'categoryId', 'quantity', 'price', 'discount', 'trueAmount', 'purchasePrice', 'costTotal', 'grossProfit', 'grossProfitRate', 'blandName', 'styleName', 'seasonName', 'year'];
    var groupByGoodListShowColsArr = ['goodsName', 'goodsSn', 'barCode', 'categoryId', 'quantity', 'price', 'discount', 'truePrice', 'amount',
        'trueAmount', 'blandName', 'styleName', 'seasonName', 'year'];
    var groupByOrderListShowColsArr = ['ordersSn', 'quantity', 'businessTime', 'salerName', 'clientName', 'trueTotalAmount', 'adjustmentsTotal', 'alreadyPaid', 'costTotal', 'grossProfit', 'grossProfitRate', 'storeName'];
    var groupByClientListShowColsArr = ['quantity', 'trueAmount', 'costTotal', 'grossProfit', 'grossProfitRate', 'clientName'];
    var groupByHandlerListShowColsArr = ['quantity', 'trueAmount', 'grossProfit', 'grossProfitRate', 'storeName'];
    var groupBySalerListShowColsArr = ['quantity', 'trueAmount', 'costTotal', 'grossProfit', 'grossProfitRate','salerName', 'storeName'];
    // 按销售员所属门门店汇总显示的列
    var groupBySalerComStoreListShowColsArr = ['quantity', 'trueAmount', 'storeName'];
    //按仓库所属门门店汇总显示的列
    var groupByStorehouseComStoreListShowColsArr = ['quantity', 'trueAmount', 'grossProfit', 'grossProfitRate', 'storeName'];


    // 销售明细
    var detailListSearchItemArr = ['searchKey', 'category', 'client', 'handler', 'saler', 'ordersSn', 'bland', 'color', 'size', 'style', 'material', 'year', 'season', 'storeId', 'orderStatus'];
    // 按单品汇总
    var groupBySkuListSearchItemArr = ['searchKey', 'category', 'bland', 'color', 'size', 'style', 'material', 'year', 'season', 'orderStatus', 'storeId'];
    // 按商品汇总
    var groupByGoodListSearchItemArr = ['searchKey', 'category', 'bland', 'style', 'material', 'year', 'season', 'orderStatus', 'client', 'storeId', 'saler'];
    // 按单据汇总
    var groupByOrderListSearchItemArr = ['client', 'handler', 'saler', 'ordersSn', 'storeId', 'orderStatus'];
    // 按客户汇总
    var groupByClientListSearchItemArr = ['client', 'orderStatus', 'storeId'];
    // 按操作人员汇总
    var groupByHandlerListSearchItemArr = ['handler', 'storeId', 'orderStatus'];
    // 按销售员汇总
    var groupBySalerListSearchItemArr = ['saler', 'orderStatus', 'storeId'];
    //按销售员所属门店汇总
    var groupBySalerComStoreListSearchItemArr = ['orderStatus'];
    //按仓库所属门店汇总
    var groupByStorehouseComStoreListSearchItemArr = ['storeId', 'orderStatus'];

    $(document).ready(function () {
        jQuery("#list_section").jqGrid({
            cmTemplate: {
                sortable: false
            },
            jsonReader: {
                root: 'data',
                page: 'current_page',
                total: 'last_page',
                records: 'total'
            },
            prmNames: {},
            postData: {
                beginTime: transferGMTStringtoBJTime(getDayBeginStr(new Date())),
                endTime: transferGMTStringtoBJTime(getOffsetDayBeginStr(new Date(), 1))
            },
            url: '{{ route('admin.shop.report.sales.saleDetailList') }}', // 传入后台的地址。
            //mtype: 'post', // 提交后台方式
            datatype: 'local', // local初始化时不会查询数据,json时初始化时会查询数据         得到后台传入前台的方式
            multiselect: false,
            multiSort: true,
            colModel: [{
                name: 'goodsName',
                index: 'goodsName',
                label: '商品名称',
                frozen: true,
                sortable: true
            }, {
                name: 'goodsSn',
                index: 'goodsSn',
                label: '货号',
                width: 120,
                frozen: true,
                sortable: true
            }, {
                name: 'barCode',
                index: 'barCode',
                label: '条码',
                align: "center",
                width: 120,
                frozen: true
            }, {
                name: 'colorName',
                index: 'colorName',
                width: 100,
                label: '颜色',
                align: "center",
                frozen: true
            }, {
                name: 'sizeName',
                index: 'sizeName',
                width: 100,
                label: '尺码',
                align: "center",
                frozen: true
            }, {
                name: 'categoryId',
                index: 'categoryId',
                label: '分类',
                align: "center",
                width: 80,
                formatter: categoryNamesDecode,
                frozen: true
            }, {
                name: 'blandName',
                index: 'blandName',
                label: '品牌',
                align: "left",
                width: 80,
                frozen: true,
                formatter: blandNamesDecode,
                sortable: true
            }, {
                name: 'quantity',
                index: 'quantity',
                label: "单品数量",
                align: "right",
                width: 100,
                sortable: true
            }, {
                name: 'price',
                index: 'price',
                align: "right",
                label: "吊牌价",
                width: 100,
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'amount',
                index: 'amount',
                label: "总金额",   //吊牌总金额
                align: "right",
                sorttype: "float",
                formatter: 'currency',
                sortable: true
            }, {
                name: 'discount',
                index: 'discount',
                label: "折扣(%)",
                align: "right",
                formatter: 'number'
            }, {
                name: 'truePrice',
                index: 'truePrice',
                align: "right",
                label: "折后价",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'trueAmount',
                index: 'trueAmount',
                align: "right",
                label: "成交总金额",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'purchasePrice',
                index: 'purchasePrice',
                align: "right",
                label: "采购均价",
                width: 100,
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'costTotal',
                index: 'costTotal',
                align: "right",
                label: "采购成本",
                width: 100,
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'grossProfit',
                index: 'grossProfit',
                align: "right",
                label: "毛利润",
                width: 100,
                sorttype: "float",
                formatter: 'currency',
                sortable: true
            }, {
                name: 'grossProfitRate',
                index: 'grossProfitRate',
                align: "right",
                label: "毛利率(%)",
                width: 100,
                sorttype: "float",
                sortable: true
            }, {
                name: 'ordersSn',
                index: 'ordersSn',
                align: 'center',
                //formatter: viewOrder,
                label: '单据编号'
            }, {
                name: 'salerName',
                index: 'salerName',
                align: 'center',
                label: '销售员',
                sortable: true
            }, {
                name: 'clientName',
                index: 'clientName',
                align: 'center',
                label: '客户',
                sortable: true
            }, {
                name: 'styleName',
                index: 'styleName',
                width: 120,
                align: 'center',
                label: '款式'
            }, {
                name: 'seasonName',
                index: 'seasonName',
                label: '季节',
                align: "center",
                width: 80
            }, {
                name: 'year',
                index: 'year',
                label: '年份',
                align: "center",
                //formatter : yearFromater,
                width: 90
            }, {
                name: 'trueTotalAmount',
                index: 'trueTotalAmount',
                label: "单据总金额",
                align: "right",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'adjustmentsTotal',
                index: 'adjustmentsTotal',
                label: "总优惠金额",
                align: "right",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'wipeZero',
                index: 'wipeZero',
                label: "抹零金额",
                align: "right",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'alreadyPaid',
                index: 'alreadyPaid',
                label: "实收金额",
                align: "right",
                sorttype: "float",
                formatter: 'currency'
            }, {
                name: 'businessTime',
                index: 'businessTime',
                width: 130,
                align: 'center',
                label: '单据日期',
                sortable: true
            }, {
                name: 'storeName',
                index: 'storeName',
                label: '所属门店',
                align: "center",
                width: 120
            }, {
                name: 'id',
                index: 'id',
                hidden: true,
                label: 'id'
            }], // --显示的列。
            pager: "#list_section_pager", // --得到分页的层
            rownumbers: false, // --是否在表格最前端添加1列为自动编号
            rowNum: 18, // --一页显示几行？
            page: 1, // --从弟几页开始
            rowlist: [10, 20, 30], // --多少页一段
            height: "100%",
            width: "100%",
            viewrecords: true,
            autowidth: true,
            shrinkToFit: false,
            gridComplete: function () {
                $("#list_section").setGridWidth($("#list_section").parent().parent().parent().parent().parent().width());
                getScope("SaleReportModule").loadingData = false;
                var dataListType = getScope("SaleReportModule").dataListType;
                // 根据dataListType设置tab
                $("ul#myTab li:not(." + dataListType + ")").removeClass("active").css("background-color", "white");
                $("ul#myTab li." + dataListType).addClass("active");
            },
            loadComplete: function () {
                adjustFrozenColumnHeight('list_section');
                disableTarget(getScope("SaleReportModule").target, false);
            },
            loadError: function () {
                disableTarget(getScope("SaleReportModule").target, false);
            },
        }).jqGrid('navGrid', '#list_section_pager', {
            refresh: false,
            add: false,
            edit: false,
            del: false,
            search: false,
            sortable: false
        }, {
            closeOnEscape: true,
            closeAfterEdit: true
        }, {
            closeOnEscape: true,
            closeAfterAdd: true,
            serializeEditData: function (data) {
                return $.param($.extend({}, data, {
                    id: ''
                }));
            }
        });

        // 自适应宽度
        $(window).resize(function () {
            $("#list_section").setGridWidth($("#list_section").parent().parent().parent().parent().parent().width());
        });

        //修复排序列表头样式
        var myGrid = $("#list_section");
        var cm = myGrid[0].p.colModel;
        $.each(myGrid[0].grid.headers, function (index, value) {
            var cmi = cm[index], colName = cmi.name;
            if (cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
                $('div.ui-jqgrid-sortable', value.el).addClass('sortable');
                $('div.ui-jqgrid-sortable', value.el).prepend('<span class="sortable-icon"></span>');
            }
        });

        // 设置jqgrid表头对齐方式
        setGridLabelAlign('list_section', 'quantity,price,discount,truePrice,amount,trueAmount,purchasePrice,trueTotalAmount,grossProfit,grossProfitRate,alreadyPaid,wipeZero', 'right');
        setGridLabelAlign('list_section', 'goodsName,goodsSn', 'categoryId', 'left');
        setGridLabelClass('list_section', 'quantity,trueAmount,grossProfit,grossProfitRate', 'sortable-align-fix');

        // 冻结列
        jQuery("#list_section").jqGrid('setFrozenColumns');
        adjustFrozenDivHeight('list_section');

        // 加载页面后执行方法查询数据
        if ($.getUrlParam("callMethod")) {
            eval($.getUrlParam("callMethod") + "(" + $.getUrlParam("params") + ")");
        } else {
            getScope("SaleReportModule").searchList();
            getScope("SaleReportModule").getSumData();
        }
        // 默认是显示按销售明细页面,控制显示列
        setGridColDisplay(detailListShowColsArr);

        /*if (onLoadFromGoodsSummary) {
         var scope = getScope("SaleReportModule");
         var queryvo = onLoadFromGoodsSummary;

         scope.searchModel.timePeriod = 'other'
         scope.searchModel.beginTime = new Date(queryvo.beginTime);
         scope.searchModel.endTime = new Date(queryvo.endTime);
         scope.searchModel.searchKey = queryvo.searchKey;
         scope.showSearchTab = true;
         setTimeout(function () {
         scope.$apply(function (scope) {
         scope.dataListType = 'groupBySkuList'
         scope.searchList();
         scope.getSumData();
         });
         }, 1000);
         }*/
    });

    /***************************** angularJs模块 ***************************************/
    var commodityApp = angular.module('JxApp', ['JxApp.mulsel', "checklist-model", "ui.bootstrap.tpls", 'ui.bootstrap.datepicker', 'JxApp.levelsel']);

    commodityApp.controller("SaleReportModule", function ($scope, $filter, $http) {

        $scope.loadingData = false;
        $scope.dataListType = 'saleRetailList';
        $scope.searchForm = {};
        $scope.getSumData = function (searchParam) {
            if (!$scope.searchModel.beginTime) {
                return;
            } else if (!$scope.searchModel.endTime) {
                return;
            } else if (addDate($scope.searchModel.beginTime, 366).getTime() < $scope.searchModel.endTime.getTime()) {
                return;
            }

            if (!searchParam) {
                searchParam = angular.copy($scope.searchParam);
            }

            searchParam.beginTime = getDayBegin($scope.searchModel.beginTime);
            searchParam.endTime = getOffsetDayBegin($scope.searchModel.endTime, 1);
            searchParam.dataListType = $scope.dataListType;
            $scope.sumDataLoading = true;
            $http.get($scope.saleSumReportUrl, {params: searchParam}).success(function (result) {

                $scope.sumQuantity = result.sumQuantity;
                $scope.sumTrueAmount = result.sumTrueAmount;
                $scope.sumGrossProfit = result.sumGrossProfit;
                $scope.avgGrossProfitRate = result.avgGrossProfitRate;

                $scope.sumDataLoading = false;
            });
        };

        //查询函数
        $scope.searchList = function () {
            $scope.loadingData = true;
            var categoryIds = getChildIds(allCategoryList, $scope.searchModel.categoryId);
            var vToday = new Date();
            if ($scope.searchModel.timePeriod == 'today') {
                $scope.searchModel.beginTime = vToday;
                $scope.searchModel.endTime = vToday;
            } else if ($scope.searchModel.timePeriod == 'yesterday') {
                var vYesterday = getYesterday(vToday);
                $scope.searchModel.beginTime = vYesterday;
                $scope.searchModel.endTime = vYesterday;
            } else if ($scope.searchModel.timePeriod == 'thisWeek') {
                // 上周的今天再加1天
                $scope.searchModel.beginTime = addDate(vToday, -6);
                $scope.searchModel.endTime = vToday;
            } else if ($scope.searchModel.timePeriod == 'thisMonth') {
                // 算上今天，倒推29天
                $scope.searchModel.beginTime = addDate(vToday, -29);
                $scope.searchModel.endTime = vToday;
            } else if ($scope.searchModel.timePeriod == 'other') {
                if (!$scope.searchModel.beginTime) {
                    alert('查询开始日期不可为空');
                    return;
                } else if (!$scope.searchModel.endTime) {
                    alert('查询结束日期不可为空');
                    return;
                } else if (addDate($scope.searchModel.beginTime, 366).getTime() < $scope.searchModel.endTime.getTime()) {
                    alert('查询时间不可超过366天');
                    return;
                }
            }

            var searchParam = {
                searchKey: $scope.searchModel.searchKey,
                beginTime: transferGMTStringtoBJTime(getDayBeginStr($scope.searchModel.beginTime)),
                endTime: transferGMTStringtoBJTime(getOffsetDayBeginStr($scope.searchModel.endTime, 1)),
                clientId: $scope.searchModel.clientId,
                handlerId: $scope.searchModel.handlerId,
                salerId: $scope.searchModel.salerId,
                ordersSn: $scope.searchModel.ordersSn,
                categoryId: categoryIds,
                blandId: $scope.searchModel.blandId,
                colorId: $scope.searchModel.colorIds,
                sizeId: $scope.searchModel.sizeIds,
                styleId: $scope.searchModel.styleId,
                year: $scope.searchModel.year,
                seasonId: $scope.searchModel.seasonId,
                storeId: $scope.searchModel.storeId,
                orderStatus: $scope.searchModel.orderStatus,
            };

            if (!contains($scope.curSearchItemArr, 'searchKey')) {
                delete searchParam.searchKey;
            }
            if (!contains($scope.curSearchItemArr, 'client')) {
                delete searchParam.clientId;
            }
            if (!contains($scope.curSearchItemArr, 'handler')) {
                delete searchParam.handlerId;
            }
            if (!contains($scope.curSearchItemArr, 'saler')) {
                delete searchParam.salerId;
            }
            if (!contains($scope.curSearchItemArr, 'ordersSn')) {
                delete searchParam.ordersSn;
            }
            if (!contains($scope.curSearchItemArr, 'category')) {
                delete searchParam.categoryId;
            }
            if (!contains($scope.curSearchItemArr, 'bland')) {
                delete searchParam.blandId;
            }
            if (!contains($scope.curSearchItemArr, 'color')) {
                delete searchParam.colorId;
            }
            if (!contains($scope.curSearchItemArr, 'size')) {
                delete searchParam.sizeId;
            }
            if (!contains($scope.curSearchItemArr, 'style')) {
                delete searchParam.styleId;
            }

            if (!contains($scope.curSearchItemArr, 'year')) {
                delete searchParam.year;
            }
            if (!contains($scope.curSearchItemArr, 'season')) {
                delete searchParam.seasonId;
            }
            if (!contains($scope.curSearchItemArr, 'storeId')) {
                delete searchParam.storeId;
            }

            // 手动清空postdata
            $("#list_section").setGridParam({
                postData: null
            });
            $("#list_section").setGridParam({
                postData: {
                    page: 1
                }
            });
            //取消上个button禁用
            disableTarget($scope.target, false, true);
            $scope.target = getEvtTarget();
            disableTarget($scope.target, true);
            $("#list_section").setGridParam({datatype: 'json'});
            $("#list_section").jqGrid("setGridParam", {
                postData: searchParam,
                url: $scope.saleReportUrl
            }).trigger("reloadGrid", [{
                page: 1
            }]); // 重新载入Grid表格
            $scope.searchParam = searchParam;//保存最后一次查询结果对应的查询条件,以供用作获取统计数据的查询条件
        };

        $scope.init = function () {
            $scope.showCountData = false;

            $scope.searchModel = {
                timePeriod: 'today',
                beginTime: new Date(),
                endTime: new Date(),
                orderStatus: 2,
            };
            $scope.searchParam = {
                beginTime: getDayBeginStr($scope.searchModel.beginTime),
                endTime: getOffsetDayBeginStr($scope.searchModel.endTime, 1)
            };

            $scope.showSearchTab = true;
            $scope.saleReportUrl = '{{ route('admin.shop.report.sales.saleDetailList') }}';
            $scope.saleSumReportUrl = '{{ route('admin.shop.report.sales.saleDetailListSum') }}';
            $scope.sumDataLoading = true;
            $scope.allCategory = allCategory;
            $scope.curSearchItemArr = detailListSearchItemArr;
            $scope.blands = strBlandListJson;
            $scope.seasons = strSeasonListJson;
            $scope.allYears = allYears;
            $scope.allStyleJson = strStyleListJson;
            $scope.allColorJson = allColors;
            $scope.allSizeJson = allSizes;
        };

        $scope.init();

        $scope.getShowDataCountText = function () {
            if ($scope.showCountData) {
                return '收起统计数据';
            } else {
                return '展示统计数据';
            }

        };

        $scope.changeShowDataCount = function () {
            $scope.showCountData = !$scope.showCountData;
        };

        $scope.refreshTimePeriod = function () {
            var vToday = new Date();
            if (!$scope.searchModel.beginTime || !$scope.searchModel.endTime) {
                $scope.searchModel.timePeriod = 'other';
            } else if (getDayBeginStr($scope.searchModel.beginTime) == getDayBeginStr(vToday)
                    && getDayBeginStr($scope.searchModel.endTime) == getDayBeginStr(vToday)) {
                $scope.searchModel.timePeriod = 'today';
            } else if (getDayBeginStr($scope.searchModel.beginTime) == getDayBeginStr(getYesterday(vToday))
                    && getDayBeginStr($scope.searchModel.endTime) == getDayBeginStr(getYesterday(vToday))) {
                $scope.searchModel.timePeriod = 'yesterday';
            } else if (getDayBeginStr($scope.searchModel.beginTime) == getDayBeginStr(addDate(vToday, -6))
                    && getDayBeginStr($scope.searchModel.endTime) == getDayBeginStr(new Date())) {
                $scope.searchModel.timePeriod = 'thisWeek';
            } else if (getDayBeginStr($scope.searchModel.beginTime) == getDayBeginStr(addDate(vToday, -29))
                    && getDayBeginStr($scope.searchModel.endTime) == getDayBeginStr(new Date())) {
                $scope.searchModel.timePeriod = 'thisMonth';
            } else {
                $scope.searchModel.timePeriod = 'other';
            }
        };

        $scope.$watch('searchModel.beginTime', function () {
            $scope.refreshTimePeriod();
        });

        $scope.$watch('searchModel.endTime', function () {
            $scope.refreshTimePeriod();
        });

        $scope.isShowSearchItem = function (itemName) {
            return contains($scope.curSearchItemArr, itemName);
        };

        $scope.exportAsExcel = function () {
            var sidxParam = '';
            var sordParam = '';

            var postData = $("#list_section").jqGrid("getGridParam", "postData");

            if (postData.sidx) {
                sidxParam = '&sidx=' + postData.sidx;
            }
            if (postData.sord) {
                sordParam = '&sord=' + postData.sord;
            }
            window.open(base + '/admin/inner/excelImport/report/saleDetailListExcel.ac?jsonUrl=' + $scope.saleReportUrl + sidxParam + sordParam + '&' + $.param($scope.searchParam));
        };

        $scope.helpUrl = GL_CONS.HELP_URL.saleReportHelp;


    });

    $(document).on('click.modal.data-api', '[data-toggle="modal-filter"]', function (e) {
        var $this = $(this);
        var modalUrl = $(this).data('url');

        var sidxParam = '';
        var sordParam = '';

        var postData = $("#list_section").jqGrid("getGridParam", "postData");

        if (postData.sidx) {
            sidxParam = '&sidx=' + postData.sidx;
        }

        if (postData.sord) {
            sordParam = '&sord=' + postData.sord;
        }

        var purchaseReportUrl = '';
        var searchParam = getScope("SaleReportModule").searchParam;
        searchParam.dataListType = getScope("SaleReportModule").dataListType;

        var url = '{{ route('admin.shop.report.sales.saleDetailListExcel') }}?jsonUrl=' + purchaseReportUrl + sidxParam + sordParam + '&' + $.param(searchParam);


        $(this).data('link', url);

        if (modalUrl) {
            var $target = $($this.attr('data-target'));
            $target.modal('show');
            $target.html('').load(modalUrl, function () {

            });
        }
    });


    /**
     * 标签页切换事件
     */
    $('#myTab a').click(function (e) {
        if (getScope("SaleReportModule").loadingData) {
            return;
        }

        e.preventDefault();
        $(this).tab('show');
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        if (getScope("SaleReportModule").loadingData) {
            return;
        }

        if ($(e.target).attr('href') == "#saleRetailList") {
            getScope("SaleReportModule").dataListType = 'saleRetailList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleDetailList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = detailListSearchItemArr;
            });
            setGridColDisplay(detailListShowColsArr);
            jQuery("#list_section").jqGrid("setLabel", "storeName", "仓库所属门店", {});
        } else if ($(e.target).attr('href') == "#groupBySkuList") {
            getScope("SaleReportModule").dataListType = 'groupBySkuList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleGroupBySkuList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = groupBySkuListSearchItemArr;
            });
            setGridColDisplay(groupBySkuListShowColsArr);
        } else if ($(e.target).attr('href') == "#groupByOrderList") {
            getScope("SaleReportModule").dataListType = 'groupByOrderList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleGroupByOrderList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = groupByOrderListSearchItemArr;
            });
            setGridColDisplay(groupByOrderListShowColsArr);
            jQuery("#list_section").jqGrid("setLabel", "storeName", "仓库所属门店", {});
        } else if ($(e.target).attr('href') == "#groupByClientList") {
            getScope("SaleReportModule").dataListType = 'groupByClientList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleGroupByClientList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = groupByClientListSearchItemArr;
            });
            setGridColDisplay(groupByClientListShowColsArr);
        } else if ($(e.target).attr('href') == "#groupBySalerList") {
            getScope("SaleReportModule").dataListType = 'groupBySalerList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleGroupBySalerList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = groupBySalerListSearchItemArr;
            });
            setGridColDisplay(groupBySalerListShowColsArr);
            jQuery("#list_section").jqGrid("setLabel", "storeName", "销售员所属门店", {});
        } else if ($(e.target).attr('href') == "#groupBySalerComStoreList") {
            getScope("SaleReportModule").dataListType = 'groupBySalerComStoreList';
            getScope("SaleReportModule").saleReportUrl = '{{ route('admin.shop.report.sales.saleGroupByComStoreList') }}';
            getScope("SaleReportModule").$apply(function (scope) {
                scope.curSearchItemArr = groupBySalerComStoreListSearchItemArr;
            });
            setGridColDisplay(groupBySalerComStoreListShowColsArr);
            jQuery("#list_section").jqGrid("setLabel", "storeName", "销售员所属门店", {});
        }
        // 改变businessType的标题。按单据汇总时显示为单据类型，否则显示为业务类别
        changeBusinessTypeColName(getScope("SaleReportModule").dataListType);
        // 清除列表数据
        jQuery("#list_section").jqGrid("clearGridData");
        // 查询数据
        getScope("SaleReportModule").searchList();
        getScope("SaleReportModule").getSumData();
    });


    //等候提示窗口
    $("#waitingDialog").dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 10
        },
        position: ['middle', 200],
        width: 300,
        height: 134,
        modal: true,
        resizable: false,
        open: function () {
        },
        dialogClass: "waitingDialog"
    });

    /*回车事件*/
    $('#searchForm').keypress(function (e) {
        if (e.keyCode == '13') {
            stopEvent(e);
            $('#searchBtn').click();
        }
    });

    /**
     * 品牌ID转为品牌名称
     */
    function blandNamesDecode(cellvalue, options, rowdata) {
        if (cellvalue) {

            var nameTemp = getObject(strBlandListJson, 'id', cellvalue);

            if (nameTemp) {
                return nameTemp.name;
            } else {
                return '';
            }

        } else {
            return '';
        }
    }

    /**
     * 改变businessType的标题。按单据汇总时显示为单据类型，否则显示为业务类别
     *
     * @param dataListType
     */
    function changeBusinessTypeColName(dataListType) {
        var colDisplayName = '业务类别';
        if (dataListType == 'groupByOrderList') {
            colDisplayName = '单据类型';
        }
        $("#list_section").jqGrid("setLabel", 'businessType', colDisplayName, {});
    }

    //设置jgrid表头对齐方式
    function setGridLabelAlign(gridId, colNames, alignType) {
        var colNameArr = [];
        if (colNames != undefined) {
            colNameArr = colNames.split(',');
        }
        for (var i = 0; i < colNameArr.length; i++) {
            $("#" + gridId).jqGrid("setLabel", colNameArr[i], "", {
                "text-align": alignType
            });
        }
    }
    ;

    //设置jgrid表头样式
    function setGridLabelClass(gridId, colNames, css) {
        var colNameArr = [];
        if (colNames != undefined) {
            colNameArr = colNames.split(',');
        }
        for (var i = 0; i < colNameArr.length; i++) {
            $("#" + gridId).jqGrid("setLabel", colNameArr[i], "", css);
        }
    }
    ;

    //设置jgrid列是否显示
    function setGridColDisplay(showColsArr) {
        jQuery("#list_section").jqGrid('destroyFrozenColumns');
        for (var i = 0; i < jqgridAllColsArr.length; i++) {
            if (contains(showColsArr, jqgridAllColsArr[i])) {
                console.log(jqgridAllColsArr[i])
                jQuery("#list_section").setGridParam().showCol(jqgridAllColsArr[i]);
            } else {
                jQuery("#list_section").setGridParam().hideCol(jqgridAllColsArr[i]);
            }
        }
        jQuery("#list_section").jqGrid('setFrozenColumns');
    }


    var getChildIds = function (list, startPid) {
        var ids = startPid;

        if (startPid != undefined && startPid != '') {
            if (list != undefined && list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    if (list[i]['pid'] == startPid) {
                        ids = ids + ',' + getChildIds(list, list[i]['id']);
                    }
                }

                return ids;
            } else {
                return startPid;
            }
        } else {
            return '';
        }

    };

    /**
     * 分类ID转为分类名称
     */
    function categoryNamesDecode(cellvalue, options, rowdata) {
        if (cellvalue) {

            var nameTemp = getObject(allCategoryList, 'id', cellvalue);

            if (nameTemp) {
                return nameTemp.name;
            } else {
                return '';
            }

        } else {
            return '';
        }
    }

    /**
     * 跳转单据链接
     */
    function viewOrder(cellvalue, options, rowdata) {
        if (rowdata.ordersSn) {
            if (rowdata.ordersSn.indexOf("LS") != -1) {

                return '<a href="'
                        + '/is/admin/inner/sale/retailOrdersList.ac?mid=4&onLoadOrdersSn='
                        + rowdata.ordersSn + '" target="_blank">'
                        + rowdata.ordersSn + '</a>';
            } else if (rowdata.ordersSn.indexOf("TH") != -1) {
                return '<a href="'
                        + '/is/admin/inner/sale/rejectOrdersList.ac?mid=4&onLoadOrdersSn='
                        + rowdata.ordersSn + '" target="_blank">'
                        + rowdata.ordersSn + '</a>';
            } else {
                return '<a href="'
                        + '/is/admin/inner/sale/wholesaleOrdersList.ac?mid=4&onLoadOrdersSn='
                        + rowdata.ordersSn + '" target="_blank">'
                        + rowdata.ordersSn + '</a>';
            }
        }
    }

    /**
     * 显示“是”或者“否” 1-是 2-否
     */
    function yearFromater(cellvalue, options, rowdata) {
        if (!cellvalue) {
            return '';
        } else if (parseFloat(cellvalue) - parseInt(cellvalue) == 0.5) {
            return cellvalue == '' ? '' : (parseInt(cellvalue) + '下');
        } else {
            return cellvalue == '' ? '' : (parseInt(cellvalue) + '上');
        }
    }

    /* 修复Jqgrid冻结列高度函数 */
    function adjustFrozenDivHeight(listId) {
        var bdivTop = -1;

        if (navigator.userAgent.toLowerCase().match(/opera/)) {
            divTop = 0;
            bdivTop = 0;
        }

        $('#gview_' + listId + ' .frozen-bdiv').css({
            top: $('#gview_' + listId + ' .frozen-bdiv').position().top + bdivTop
        });
    }

    //检查每一行冻结行高度是否和未冻结行高度一致
    function adjustFrozenColumnHeight(listId) {
        $('#' + listId + '_frozen tr').slice(1).each(function () {

            var frozenTdHeight = parseFloat($('td:first', this).height());
            var normalHeight = parseFloat($(' #' + listId + ' #' + $(this).attr('id')).find('td:first').height());

            // 如果冻结的列高度小于未冻结列的高度则hack之
            if (frozenTdHeight != normalHeight) {

                $('td', this).each(function () {

                    /* 浏览器差异高度hack */
                    var space = 0; // opera默认使用0就可以
                    /*				if (navigator.userAgent.toLowerCase().match(/chrome/)) {
                     space = 0.6;
                     } else if (navigator.userAgent.toLowerCase().match(/msie/)) {
                     space = -0.2;
                     } else if (navigator.userAgent.toLowerCase().match(/mozilla/)) {
                     space = 0.3;
                     }*/
                    $(this).style('height', parseFloat(normalHeight + space) + "px", 'important');
                    /*
                     * div.style('color', 'blue', 'important');
                     * $(this).css("cssText","height:"+parseFloat(normalHeight +
                     * space)+"px !important");
                     */
                    /*
                     * if (!$(this).attr('style') ||
                     * $(this).attr('style').indexOf('height:') == -1) {
                     * $(this).attr('style', $(this).attr('style') + ";height:" +
                     * (normalHeight + space) + "px !important"); }
                     */
                });
            }
            $('#gview_' + listId + ' .ui-jqgrid-bdiv:eq(1)').style('height', $('#gview_' + listId + ' .ui-jqgrid-bdiv:first').height() + 'px', 'important');

        });

        $('#gview_' + listId + ' .frozen-bdiv').style('height', $('table#' + listId + '_frozen').height() + 'px', 'important');//避免冻结的DIV挡住列表的横向滚动条
    }

    //从经营汇总的销量走势中点击节点跳转到销售报表时查询对应的数据。
    function querySaleReport(selectDate, categoryId, goodsSn, colorId, sizeId) {
        var scope = getScope("SaleReportModule");
        scope.loadDefaultData = false;
        scope.searchModel.beginTime = new Date(selectDate);
        scope.searchModel.endTime = new Date(selectDate);
        scope.searchModel.categoryId = categoryId;
        scope.searchModel.searchKey = goodsSn;
        scope.refreshTimePeriod();
        scope.searchModel.timePeriod = 'other';
        scope.showSearchTab = true;
        scope.searchList();
        scope.getSumData();
    }

</script>